from django.contrib.auth.hashers import make_password

# Create your views here.

from rest_framework.response import Response
from rest_framework.views import APIView
from django.conf import settings  # 邮件要导入settings里面的邮件配置
from itsdangerous import TimedJSONWebSignatureSerializer

# 发送邮件加密使用
token_serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 1800)

from .serializer import *
from app01.tasks import send_email_task
import re


class RoleView(APIView):
    """
    角色增加
    """

    def post(self, request):
        name = request.data.get('name')
        print(name, '1111111111111111')
        role_obj = RoleModel.objects.filter(name=name)
        if role_obj:
            return Response('角色已存在')
        role_ser = RoleSer(data=request.data)
        if role_ser.is_valid():
            role_ser.save()
            return Response('角色添加成功')
        else:
            return Response({'error': role_ser.errors})


class RegisterView(APIView):
    """
    @ author: wangxiaochen
    @ date: 2020-9-27
    注册：
        {'username':['xxx'],'password1':['xxxxx'],'password2':[''xxx],
        'phone':['133333'],'email':['xxxx'],'role':['1']}
    """

    def post(self, request):
        # 获取网页提交数据
        username = request.data.get('username')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        phone = request.data.get('phone')
        email = request.data.get('email')
        role_id = request.data.get('role')
        print(password2, password2)

        # 判断数据的完整性
        # if not all([username,password1,password2,phone,email,role_id]):
        #     return Response({'msg':'数据不完整','code':400})

        # 获取数据库中数据，用来判断用户是否存在
        user_obj = UserModel.objects.filter(username=username)

        # 判断用户
        if user_obj:
            return Response({'mssg': '用户已存在', 'code': 400})
        if not re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.com', email):
            return Response({'msg': '邮箱不符合规则', 'code': 400})

        if not re.match(r'^1[3456789]\d{9}$', phone):
            return Response({'msg': '电话不符合规则', 'code': 400})

        # 判断两次密码
        if password1 == password2:

            # 反序列化添加
            user_data = {'username': username, 'password': make_password(password2),
                         'phone': phone, 'email': email, 'role': role_id}
            ser = UserSer(data=user_data)

            # 校验
            if ser.is_valid():
                ser.save()
                # 发邮件
                # 异步
                user_info = {'user_id': ser.data.get('id')}
                token = token_serializer.dumps(user_info).decode()
                send_email_task(username, token, email)
                # 发手机验证码

                return Response({'msg': '注册成功', 'code': '200'})
            else:
                return Response({'error': ser.errors, 'code': 400})
        else:
            return Response({'msg': '两次密码不一致', 'code': 400})


class ActiveView(APIView):
    def get(self, request):
        token = request.query_params.get('token')
        if token:
            return Response({'msg': 'ok', 'token': token})
